//
//  RaiderDetailViewController.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/9/5.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "RaiderDetailVC.h"
#import <WebKit/WebKit.h>
#import "LinePreDetailVC.h"
#import "GuiderDetailVC.h"
#import "ScenicDescribeVC.h"
#import "IGShare.h"
@interface RaiderDetailVC ()<WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler,UIScrollViewDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIImageView *placeholdImageView;

@property (nonatomic)BOOL hasScroll1, hasScroll2;
@end

@implementation RaiderDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setup];
}

- (void)showShareSheet{
    [self popSheet];
}

- (void)setup {
    
    [self rightBarButtonWithImageName:@"分享" selector:@selector(showShareSheet)];
    self.barBGAlpha = 0;
    self.customBarStyle = UIStatusBarStyleLightContent;
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    [config.userContentController addScriptMessageHandler:self name:@"imguider"];
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    self.webView.scrollView.delegate = self;
    [self.view addSubview:self.webView];
    
    if (self.raider.url.length == 0) {
        
        [IGUtil showToast:MYLocalizedString(@"HOMEPAGE_STRATEGY_UNKONWN", nil)];
        return;
    }
    
    self.placeholdImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"webplacehold"]];
    self.placeholdImageView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.placeholdImageView.userInteractionEnabled = YES;
    [self.view addSubview:self.placeholdImageView];
    UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    indicatorView.tag = 10086;
    [self.placeholdImageView addSubview:indicatorView];
    indicatorView.frame = CGRectMake(kScreenWidth / 2 - 50, kScreenHeight / 2 - 50, 100, 100);
    [indicatorView startAnimating];
    
   
    
    NSString *url = [NSString stringWithFormat:@"%@%@?platform=ios&lang=%@&country=%@",kShareURLStr,self.raider.url, [AppManager sharedManager].language, [AppManager sharedManager].currencyCode];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    
    // ios 11  scrollvew 的位置调整
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior =UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
}


- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    NSDictionary *obj = message.body;
    
    NSString *strSel = obj[@"method"];
    NSDictionary *param = obj[@"params"];
    
    if (strSel && param.count > 0) {
        
        strSel = [strSel stringByAppendingString:@":"];
    }
    
    SEL sel = NSSelectorFromString(strSel);
    
    if (sel && [self respondsToSelector:sel]) {
        
        [self performSelector:sel withObject:param];
    }
    
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    
    // 禁用选中效果
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'" completionHandler:nil];
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'" completionHandler:nil];
    
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    
    self.placeholdImageView.hidden = YES;
    
    UIActivityIndicatorView *indicatorView = [self.placeholdImageView viewWithTag:10086];
    
    if ([indicatorView isKindOfClass:[UIActivityIndicatorView class]]) {
        [indicatorView stopAnimating];
    }
    
    [self.placeholdImageView removeFromSuperview];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    
    UIActivityIndicatorView *indicatorView = [self.placeholdImageView viewWithTag:10086];
    
    if ([indicatorView isKindOfClass:[UIActivityIndicatorView class]]) {
        [indicatorView stopAnimating];
    }
    [self.placeholdImageView removeFromSuperview];
}

#pragma mark -webinterface

- (void)jumpline:(NSDictionary *)params {
    
    NSString * lineID = params[@"lineid"];
    LinePreDetailVC * lineDetaiVC = [IGUtil loadViewController:@"LinePreDetailVC" storyboard:@"LineDetail"];;
    
    lineDetaiVC.lineid = lineID;
    
    [self.navigationController pushViewController:lineDetaiVC animated:YES];
}

- (void)jumpscenic:(NSDictionary *)params {
    
    NSString * scenicID = params[@"scenicid"];
    
    ScenicDescribeVC * vc = [[ScenicDescribeVC alloc] init];

    vc.scenicid = scenicID;
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)jumpguider:(NSDictionary *)params {
    
    NSString *guiderid = params[@"guiderid"];
    
    GuiderDetailVC * vc = [GuiderDetailVC new];
    vc.guiderID = guiderid;
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat distance = scrollView.contentOffset.y;
    
    self.barBGAlpha = distance / kNavigationBarHeight;
    
    if (distance >= kNavigationBarHeight) {
        
        if (self.hasScroll1) {
            
            return;
        }
        
        self.hasScroll1 = YES;
        self.hasScroll2 = NO;
        self.webView.frame = CGRectMake(0, kNavigationBarHeight, kScreenWidth, kScreenHeight - kNavigationBarHeight);
        self.webView.scrollView.contentOffset = CGPointMake(0, distance + kNavigationBarHeight);
        
        self.title = self.raider.title;
        
    } else {
        
        if (self.hasScroll2) {
            
            return;
        }
        
        self.hasScroll1 = NO;
        self.hasScroll2 = YES;
        self.webView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        
        self.webView.scrollView.contentOffset = CGPointMake(0, distance - kNavigationBarHeight);
        
        self.title = @"";
    }
    
    if (self.barBGAlpha > 0.5) {
        
        self.customBarStyle = UIStatusBarStyleDefault;
    } else {

        self.customBarStyle = UIStatusBarStyleLightContent;
    }
}



#pragma mark - SnailSheetViewDelegate

- (void)sheetView:(SnailSheetView *)sheetView didSelectItemAtSection:(NSInteger)section index:(NSInteger)index {
    
    SnailSheetItemModel *model = [self sheetModels][section][index];
    
    @weakify(self)
    self.sl_popupController.didDismiss = ^(SnailPopupController * _Nonnull popupController) {
        @strongify(self)
        
        [IGShare shareWebPageToPlatformType:model.platformType withURL:[NSString stringWithFormat:@"%@%@?platform=ios&lang=%@&country=%@",kShareURLStr,self.raider.url, [AppManager sharedManager].language, [AppManager sharedManager].currencyCode] title:self.raider.title descr:MYLocalizedString(@"SHARE_TIPS_MESSAGE", nil) thumImage:self.raider.pictureArray.firstObject object:nil type:2 completion:^(id result, NSError *error) {
            
        }];
    };
    [self.sl_popupController dismiss];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
